package com.csw.mybatisSpringboot.config.quanXian;

import org.apache.commons.lang3.StringUtils;

public class EscapeUtils {
    /**
     * 转义字符%和_
     *
     * @param str 目标字符串
     * @return
     */
    public static String escapeStr(String str) {
        if (str.startsWith("%") || str.startsWith("_")) {
            str = "\\" + str;
        }

        if (str.endsWith("_")) {
            int index = str.indexOf("_");
            str = str.substring(0, index) + "\\" + "_";
        }

        if (str.endsWith("%")) {
            int index = str.indexOf("%");
            str = str.substring(0, index) + "\\\\" + "%";
        }

        return str;
    }

    public static String escapeSqlSpecialChars(String str) {
        if (StringUtils.isNotBlank(str)) {
            str = str.replaceAll("\\\\", "\\\\\\\\");
            str = str.replaceAll("_", "\\\\_");
            str = str.replaceAll("%", "\\\\%");
        }
        return str;
    }

}
